package cn.itcast.wanxinp2p.consumer.service.impl;

import cn.itcast.exception.BusinessException;
import cn.itcast.wanxinp2p.account.model.AccountRegisterDTO;
import cn.itcast.wanxinp2p.consumer.agent.FeignApi;
import cn.itcast.wanxinp2p.consumer.common.ConsumerErrorCode;
import cn.itcast.wanxinp2p.consumer.mapper.ConsumerMapper;
import cn.itcast.wanxinp2p.consumer.model.ConsumerDTO;
import cn.itcast.wanxinp2p.consumer.model.ConsumerRegisterDTO;
import cn.itcast.wanxinp2p.consumer.service.ConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ConsumerServiceImpl implements ConsumerService {

    @Autowired
    private ConsumerMapper consumerMapper;

    @Autowired
    private FeignApi feignClient;

    @Override
    public Integer checkMobile(String mobile) {
        //根据手机号查询用户，存在返回1 不存在返回0
        Integer count = consumerMapper.checkMobile(mobile);
        if(count == 0){
            return 0;
        }else{
            return 1;
        }
    }

    @Override
    public void register(ConsumerRegisterDTO consumerRegisterDTO) {
        //1、检测是否已注册，如果已经注册，则抛出 ConsumerErrorCode.E_140107 异常
        Integer integer = checkMobile(consumerRegisterDTO.getMobile());
        if(integer == 1){
            throw new BusinessException(String.valueOf(ConsumerErrorCode.E_140107));
        }
        //2、如果用户没有注册，则保存该用户数据 到 consumer 表中
        ConsumerDTO consumerDTO = new ConsumerDTO();
        consumerDTO.setUsername(consumerRegisterDTO.getUsername());
        consumerDTO.setMobile(consumerDTO.getMobile());
        consumerMapper.add(consumerDTO);
        //3、并通过Feign远程调用 统一账号服务 实现 账号的保存

        AccountRegisterDTO accountRegisterDTO = new AccountRegisterDTO();
        accountRegisterDTO.setMobile(consumerDTO.getMobile());
        accountRegisterDTO.setUsername(consumerRegisterDTO.getUsername());
        accountRegisterDTO.setPassword(consumerRegisterDTO.getPassword());

        feignClient.register(accountRegisterDTO);
    }

    //confirm
    public void confirmRegister(ConsumerRegisterDTO consumerRegisterDTO) {
        System.out.println("execute confirmRegister");
    }

    //cancle
    public void cancelRegister(ConsumerRegisterDTO consumerRegisterDTO) {
        System.out.println("execute cancelRegister");
        //TODO 删除用户
        consumerMapper.deleteByMobile(consumerRegisterDTO.getMobile());
    }
}
